<?php
class Ebay_Template extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
			    # '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'ebay_template',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	
	static function create($template)
	{
		$judge = Ebay_Template::judgeCreate($template);
		
		if ($judge['ack'] == SUCCESS)
		{
			$path = Helper_BSS_Normal::generate(10, Helper_BSS_Normal::getTableColunmData('ebay_template'));
			$ebay_template = new Ebay_Template();
			$ebay_template->name = $template['name'];
			$ebay_template->ebay_template_base_id = $template['ebay_template_base_id'];
			$ebay_template->shop_id = $template['shop_id'];
			$ebay_template->path = $path;
			$ebay_template->css = $template['css'];
			$ebay_template->save();
			$ebay_template_id = mysql_insert_id();
			$shop = Shop::find('id=?', $template['shop_id'])->getOne();
			if (! $shop->path)
			{
				$shop->path = Helper_BSS_Normal::generate(10, Helper_BSS_Normal::getTableColunmData('shop'));
				$shop->save();
			}
			Helper_BSS_Normal::createFolder(Q::ini('custom_system/ebay_template_local_dir') . $shop->path.'/'.$path);
			Ebay_Template_Module::update($ebay_template_id, $template['base_part_module_ids']);
			return array('ack' => SUCCESS, 'message' => '', 'ebay_template_id' => $ebay_template_id);
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge['message']);
		}
	}
	
	static function judgeCreate($template)
	{
		$belong_base = Ebay_Template_Base::find('id=?', $template['ebay_template_base_id'])->asArray()->getOne();
		if ($belong_base)
		{
			$belong_shop = Shop::find('id=?', $template['shop_id'])->asArray()->getOne();
			if ($belong_shop)
			{
				if ($template['name'])
				{
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					return array('ack' => FAILURE, 'message' => 'template name is empty!');
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'belong shop is not exists!');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'belong base is not exists!');
		}
	}
	
	static function edit($template)
	{
		$judge = Ebay_Template::judgeEdit($template);
		if ($judge['ack'] == SUCCESS)
		{
			$edit_template = Ebay_Template::find('id=?', $template['id'])->getOne();
			$edit_template->name = $template['name'];
			$edit_template->css = $template['css'];
			$edit_template->save();
			$shop = Shop::find('id=?', $edit_template->shop_id)->getOne();
			if (! $shop->path)
			{
				$shop->path = Helper_BSS_Normal::generate(10, Helper_BSS_Normal::getTableColunmData('shop'));
				$shop->save();
			}
			Helper_BSS_Normal::createFolder(Q::ini('custom_system/ebay_template_local_dir') . $shop->path . '/' . $edit_template->path);
			Ebay_Template_Module::update($template['id'], $template['base_part_module_ids']);
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	static function judgeEdit($template)
	{
		$exist_template = Ebay_Template::find('id=?', $template['id'])->asArray()->getOne();
		if ($exist_template)
		{
			$belong_base = Ebay_Template_Base::find('id=?', $exist_template['ebay_template_base_id'])->asArray()->getOne();
			if ($belong_base)
			{
				if ($template['name'])
				{
					if (! empty($template['base_part_module_ids']))
					{
						foreach ($template['base_part_module_ids'] as $id)
						{
							$base_part_module = Ebay_Template_Base_Part_Module::find('ebay_template_base_part_module.id=?', $id)
								->joinLeft('ebay_template_base_part', 'ebay_template_base_id', 'ebay_template_base_part.id=ebay_template_base_part_module.ebay_template_base_part_id') 
								->asArray()->getOne();
							if ($base_part_module['ebay_template_base_id'] != $belong_base['id'])
							{
								return array('ack' => FAILURE, 'message' => 'Select the template base part module error!');
							}
						}
					}
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					return array('ack' => FAILURE, 'message' => 'template name is empty!');
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'belong base is not exists!');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'template is not exists!');
		}
	}
	
	static function getTemplatePreview($template_id, $type)
	{
		$template = Ebay_Template::find('ebay_template.id=?', $template_id)
				->joinLeft('ebay_template_base', 'path as base_path, content as base_content, css as base_css', 'ebay_template_base.id=ebay_template.ebay_template_base_id')
				->joinLeft('shop', 'name as shop_name, path as shop_path, link as shop_link', 'shop.id=ebay_template.shop_id')
				->asArray()->getOne();
		if ($template)
		{
			$host_url = ($type == 'preview') ? Q::ini('custom_system/ebay_template_local_url') : Q::ini('custom_system/ebay_template_outside_base_url');
			$vars['template']['base_url'] = $host_url . $template['shop_path'] . '/' . $template['path'] . '/';
			$vars['template']['shop_name'] = $template['shop_name'];
			$vars['template']['shop_link'] = $template['shop_link'];
			$vars['base']['base_url'] = $host_url . Q::ini('custom_system/ebay_base_template_relative_path') . $template['base_path'] . '/';
			$vars['base']['part'] = Ebay_Template_Base_Part::find('ebay_template_base_id=?', $template['ebay_template_base_id'])->asArray()->getAll();
			foreach ($vars['base']['part'] as $bp)
			{
				$base_module = Ebay_Template_Base_Part_Module::find('ebay_template_base_part_id=?', $bp['id'])->asArray()->getAll();
				foreach ($base_module as $bm)
				{
					$template_module_content = Ebay_Template_Module_Content::find('ebay_template_module_content.ebay_template_module_id=ebay_template_module.id')
						->joinLeft('ebay_template_module', '', 'ebay_template_module.ebay_template_id=' . $template['id'] . ' and ebay_template_module.ebay_template_base_part_module_id=' . $bm['id'])
						->order('ebay_template_module_content.sort asc')->asArray()->getAll();
					if ($template_module_content)
					{
						$vars[$bm['variable_name']] = $template_module_content;
					}
				}
				$html = Helper_BSS_Ebtpl::parseToHtml($bp['content'], $vars);
				$html = Helper_BSS_Ebtpl::parseToHtml($html, $vars);
				$file = Q::ini('custom_system/ebay_template_local_dir') . $template['shop_path'] . '/' . $template['path'] . '/' . $bp['variable_name'].'.html';
				if (file_exists($file) && $html == file_get_contents($file))
				{
					continue;
				}
				file_put_contents(Q::ini('custom_system/ebay_template_local_dir') . $template['shop_path'] . '/' . $template['path'] . '/' . $bp['variable_name'].'.html', $html);
			}
			$base_css_file = Q::ini('custom_system/ebay_template_local_dir') . Q::ini('custom_system/ebay_base_template_relative_path') . $template['base_path'] . '/style.css'; 
			$template_css_file = Q::ini('custom_system/ebay_template_local_dir') . $template['shop_path'] . '/' . $template['path'] . '/' . 'style.css';
			if (! file_exists($base_css_file) || file_get_contents($base_css_file) != $template['base_css'])
			{
				file_put_contents($base_css_file, $template['base_css']);
			}
			if (! file_exists($template_css_file) || file_get_contents($template_css_file) != $template['css'])
			{
				file_put_contents($template_css_file, $template['css']);
			}
			$response = Helper_BSS_Ebtpl::parseToHtml($template['base_content'], $vars);
			return array('ack' => SUCCESS, 'response' => $response);
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '没有对应模板');
		}
	}
	
	static function search($condition, $cp, $ps)
	{
		$columns = array(
			'ebay_template.*',
			'ebay_template_base.name as base_name',
			'shop.name as shop_name'
		);
		$where = Ebay_Template::buildSearchCondition($condition); 
		if ($cp == 0 && $ps == 0)
		{
			$select = Ebay_Template::find($where)
				->joinLeft('ebay_template_base', '', 'ebay_template_base.id=ebay_template.ebay_template_base_id')
				->joinLeft('shop', '', 'shop.id=ebay_template.shop_id');
			$pagination = array();
		}
		else
		{
			$select = Ebay_Template::find($where)
				->joinLeft('ebay_template_base', '', 'ebay_template_base.id=ebay_template.ebay_template_base_id')
				->joinLeft('shop', '', 'shop.id=ebay_template.shop_id')
				->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$template = $select->setColumns($columns)->asArray()->getAll();
		return array(
				'ack' => SUCCESS,
				'message' => '',
				'data' => $template,
				'pagination' => $pagination
		);
	}
	
	static function buildSearchCondition($condition)
	{
		$where = '1';
		if (! empty($condition['base_id']))
		{
			$where .= ' and ebay_template.ebay_template_base_id=' . $condition['base_id'];
		}
		if (! empty($condition['shop_id']))
		{
			$where .= ' and ebay_template.shop_id=' . $condition['shop_id'];
		}
		if (! empty($condition['template_name']))
		{
			$where .= ' and ebay_template.name like \'%' . $condition['template_name'] . '%\'';
		}
		if (! empty($condition['path']))
		{
			$where .= ' and ebay_template.path=\'' . $condition['path'] . '\'';
		}
		return $where;
	}
}